package com.carpedil.shirodemo.system.controller;

import com.carpedil.shirodemo.common.annotation.RefreshFilterChain;
import com.carpedil.shirodemo.common.util.ResultVO;
import com.carpedil.shirodemo.system.model.Menu;
import com.carpedil.shirodemo.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

/**
 * 前端控制器
 *
 * @author carpedil
 * @since 2021-01-05
 */
@Controller
@RequestMapping("/menu")
public class MenuController {
  @Autowired private IMenuService menuService;

  @GetMapping("/index")
  public String toIndex() {
    return "/menu/menu-list";
  }

  @GetMapping
  public String add() {
    return "/menu/menu-add";
  }

  @GetMapping("/{menuId}")
  public String update(@PathVariable("menuId") Integer menuId, ModelMap map) {
    map.addAttribute("menu", menuService.getById(menuId));
    return "/menu/menu-add";
  }

  /**
   * tree
   *
   * @return ResultVO
   */
  @GetMapping("/tree")
  @ResponseBody
  public ResultVO tree() {
    return ResultVO.success(menuService.selectAllTree());
  }

  /**
   * 获取菜单树+自定义的根节点->导航目录
   *
   * @return ResultVO
   */
  @GetMapping("/tree/root")
  @ResponseBody
  public ResultVO getMenuRootTree() {
    return ResultVO.success(menuService.getAllMenuTreeAndRoot());
  }

  @GetMapping("/tree/root/operator")
  @ResponseBody
  public ResultVO menuAndCountOperatorTreeAndRoot() {
    return ResultVO.success(menuService.getAllMenuAndCountOperatorTreeAndRoot());
  }

  /**
   * getRootMenuChildList
   *
   * @param parentId parentId
   * @return ResultVO
   */
  @GetMapping("/list")
  @ResponseBody
  public ResultVO getRootMenuChildList(Integer parentId) {
    return ResultVO.success(menuService.getRootMenuChildList(parentId));
  }

  /**
   * swapSortOrder
   *
   * @param currentId currentId
   * @param swapId swapId
   * @return ResultVO
   */
  @PostMapping("/swap")
  @ResponseBody
  public ResultVO swapSortOrder(Integer currentId, Integer swapId) {
    menuService.swapSortOrder(currentId, swapId);
    return ResultVO.success();
  }

  @RefreshFilterChain
  @PostMapping
  @ResponseBody
  public ResultVO addMenu(Menu menu) {
    menuService.insertMenu(menu);
    return ResultVO.success();
  }

  @RefreshFilterChain
  @PutMapping
  @ResponseBody
  public ResultVO updateMenu(Menu menu) {
    menuService.updateById(menu);
    return ResultVO.success();
  }

  @RefreshFilterChain
  @DeleteMapping("/{menuId}")
  @ResponseBody
  public ResultVO deleteMenu(@PathVariable("menuId") Integer menuId) {
    menuService.deleteMenuById(menuId);
    return ResultVO.success();
  }
}
